package study_HttpClient.util;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientPool {
    public static void main(String[] args) {
        //创建连接池管理器
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

        //设置连接数
        cm.setMaxTotal(100);

        //设置主机最大连接数
        cm.setDefaultMaxPerRoute(10);

        //使用连接池管理器发送请求
        doGet(cm);
    }

    private static void doGet(PoolingHttpClientConnectionManager cm){
        //1.不是每次创建新的HttpClient,而是从连接池中获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();

        //2.创建HttpGet对象，设置url访问地址
        HttpGet httpGet = new HttpGet("http://www.baidu.com");

        CloseableHttpResponse response = null;
        try {
            //3.使用HttpClient发起请求，获取response
            response = httpClient.execute(httpGet);

            //4.解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content.length());
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            //5.关闭response
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //6.不能关闭httpClient，由连接池管理httpClient
        }
    }
}
